package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.paas.field.SaasParticularAttributePoJo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.AssembleDao;
import com.xbongbong.saas.domain.entity.AssembleProductEntity;
import com.xbongbong.saas.domain.entity.ProductBaseInfoEntity;
import com.xbongbong.saas.domain.entity.ProductStockEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.ext.AssembleEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.product.AssembleProductEnum;
import com.xbongbong.saas.enums.product.InventoryProductEnum;
import com.xbongbong.saas.help.BatchKeyHelp;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.AssembleProductModel;
import com.xbongbong.saas.model.AssembleSubDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductBaseInfoModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductStockModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/2/18 15:29
 * @since v1.0
 */
@Service("assembleModel")
public class AssembleModelImpl implements AssembleModel {

    @Resource
    private AssembleDao assembleDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private AssembleSubDataModel assembleSubDataModel;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private AssembleProductModel assembleProductModel;
    @Resource
    private ProductBaseInfoModel productBaseInfoModel;
    @Resource
    private ProductStockModel productStockModel;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private CommonHelp commonHelp;

    @Override
    public AssembleEntityExt getByKey(Long key, String corpid) {
        AssembleEntityExt assembleEntityExt = assembleDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(assembleEntityExt), IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB);
        return assembleEntityExt;
    }

    @Override
    public Integer insert(AssembleEntityExt entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer insert = assembleDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_ASSEMBLE);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB);
        return insert;
    }

    @Override
    public Integer update(AssembleEntityExt entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = assembleDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = assembleDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_ASSEMBLE);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    /**
     * 根据条件查询数据
     * @param param 查询条件
     * @return  List<AssembleEntityExt>
     * @date 2019/3/4 19:39
     * @author Jian.Wang
     */
    @Override
    public List<AssembleEntityExt> findEntitys(Map<String, Object> param) {
        List<AssembleEntityExt> entitys = assembleDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return assembleDao.getEntitysCount(param);
    }

    @Override
    public Integer deleteBatch(List<Long> idList, String corpid) throws XbbException {
        Integer integer = assembleDao.deleteBatch(idList, corpid);
        //ES根据id批量设置del=1
        paasEsModel.deleteBatch(idList, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_ASSEMBLE);

        paasFormSubDataModel.deleteBatchByDataId(idList, corpid, IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_ASSEMBLE);
        paasEsModel.delete(deleteDTO);
        Integer integer = assembleDao.deleteByKey(key, corpid);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB);
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateDataList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateDataList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateDataList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateDataList)) {
            StandardizeDataUtil.standardizeList(updateDataList);
            integer = assembleDao.updateBatch(updateDataList, corpid);
            paasEsModel.updateBatchMuchField(updateDataList, IndexTypeEnum.IDX_SAAS_ASSEMBLE);
        }
        if (!subList.isEmpty()) {
            assembleSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = assembleDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_ASSEMBLE, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            assembleSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer batchUpdateOwner(List<Long> dataIdList, String corpid, String userId, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer integer = assembleDao.batchUpdateOwner(dataIdList, corpid, userId);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (Long id : dataIdList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid+"_"+id);
            Map<String, Object> map = new HashMap<>();
            map.put(FieldTypeEnum.OWNERID.getAlias(), userId);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_ASSEMBLE);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
        return integer;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return assembleDao.findEntitys(param);
    }

    /**
     * 编辑时格式化解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     */
    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        String platForm = formatExplainDTO.getPlatform();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, AssembleEnum.IN_PRODUCTS.getAttr())) {
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.ASSEMBLE, corpid, BasicConstant.ONE, false);
                if (Objects.isNull(formatExplainDTO.getFromCopy()) || !formatExplainDTO.getFromCopy()) {
                    fieldAttrEntity.setEditable(0);
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    subExplainList.forEach(item -> item.setEditable(0));
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
                if (Objects.equals(platForm, PlatFormEnum.DINGTALK.getValue())) {
                    SaasParticularAttributePoJo saasParticularAttributePoJo = fieldAttrEntity.getSaasParticularAttributePoJo();
                    saasParticularAttributePoJo.setProductRelyAttr(AssembleEnum.INTO_WAREHOUSE_ID.getAttr());
                }
            } else if (Objects.equals(attr, AssembleEnum.OUT_PRODUCTS.getAttr())) {
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.ASSEMBLE, corpid, BasicConstant.ONE, false);
                if (Objects.isNull(formatExplainDTO.getFromCopy()) || !formatExplainDTO.getFromCopy()) {
                    fieldAttrEntity.setEditable(0);
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    subExplainList.forEach(item -> item.setEditable(0));
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
                if (Objects.equals(platForm, PlatFormEnum.DINGTALK.getValue())) {
                    SaasParticularAttributePoJo saasParticularAttributePoJo = fieldAttrEntity.getSaasParticularAttributePoJo();
                    saasParticularAttributePoJo.setProductRelyAttr(AssembleEnum.OUT_WAREHOUSE_ID.getAttr());
                }
            } else if (Objects.equals(attr, AssembleEnum.INTO_WAREHOUSE_ID.getAttr())) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, AssembleEnum.OUT_WAREHOUSE_ID.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }
        }
    }

    /**
     * 装配单编辑格式化数据格式
     *
     * @param saasAnalysisDataDTO saas编辑数据
     * @param result              要返回的jsonobject
     * @throws XbbException 参数格式错误异常
     * @throws XbbException 异常
     * @author Jian.Wang
     * @date 2019-02-21 12:23
     * @since v1.0
     **/
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
//        formatProduct4Show(result,saasAnalysisDataDTO);
        showFormatHelp.formatLinkBusiness4Show(result,AssembleEnum.OUT_WAREHOUSE_ID.getAttr(),AssembleEnum.OUT_WAREHOUSE_ID_LINKED_TEXT.getAttr(), AssembleEnum.OUT_WAREHOUSE_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result,AssembleEnum.INTO_WAREHOUSE_ID.getAttr(),AssembleEnum.INTO_WAREHOUSE_ID_LINKED_TEXT.getAttr(), AssembleEnum.INTO_WAREHOUSE_ID.getFieldType());
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, Boolean forProcess, Integer operate, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        List<AssembleProductEntity> assembleProductEntityList = new ArrayList<>();
        // 盘点单产品冗余信息
        List<ProductBaseInfoEntity> productBaseInfoEntityList = new ArrayList<>();
        Map<Long, JSONArray> refProductSeqMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> productIdList = new HashSet<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(AssembleEnum.IN_PRODUCTS.getAttr()) instanceof JSONObject) {
                JSONArray productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, AssembleEnum.IN_PRODUCTS.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(productIdList, corpid, productArray);
                formatProductList(corpid, assembleProductEntityList, productBaseInfoEntityList, productArray, productMap, 2);
            } else {
                JSONArray jsonArray = data.getJSONArray(AssembleEnum.IN_PRODUCTS.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    List<Long> productIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        // 页面传入的产品的id
                        Long productId = object.getLong(AssembleProductEnum.PRODUCT.getAttr());
                        if (Objects.nonNull(productId)) {
                            productIdIn.add(productId);
                            productIdList.add(productId);
                        }
                    }
                    // 获取产品信息
                    Map<Long, ProductEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if (productIdIn.size() >= 1) {
                        // 从产品表中获取对应的产品信息
                        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        params.put("corpid", corpid);
                        params.put("idIn", productIdIn);
                        params.put("del", 0);
                        List<ProductEntityExt> productModelEntitys = productModel.findEntitys(params);
                        if (productModelEntitys != null) {
                            for (ProductEntityExt entity : productModelEntitys) {
                                productMap.put(entity.getId(), entity);
                            }
                        }
                    }
                    formatNewProductList(corpid, assembleProductEntityList, productBaseInfoEntityList, jsonArray, productMap, 2);
                }
            }

            if (data.get(AssembleEnum.OUT_PRODUCTS.getAttr()) instanceof JSONObject) {
                JSONArray productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, AssembleEnum.OUT_PRODUCTS.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(productIdList, corpid, productArray);
                formatProductList(corpid, assembleProductEntityList, productBaseInfoEntityList, productArray, productMap, 1);
            } else {
                JSONArray jsonArray = data.getJSONArray(AssembleEnum.OUT_PRODUCTS.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    List<Long> productIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        // 页面传入的产品的id
                        Long productId = object.getLong(AssembleProductEnum.PRODUCT.getAttr());
                        if (Objects.nonNull(productId)) {
                            productIdIn.add(productId);
                            productIdList.add(productId);
                        }
                    }
                    // 获取产品信息
                    Map<Long, ProductEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if (productIdIn.size() >= 1) {
                        // 从产品表中获取对应的产品信息
                        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        params.put("corpid", corpid);
                        params.put("idIn", productIdIn);
                        params.put("del", 0);
                        List<ProductEntityExt> productModelEntitys = productModel.findEntitys(params);
                        if (productModelEntitys != null) {
                            for (ProductEntityExt entity : productModelEntitys) {
                                productMap.put(entity.getId(), entity);
                            }
                        }
                    }
                    formatNewProductList(corpid, assembleProductEntityList, productBaseInfoEntityList, jsonArray, productMap, 1);
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0
            assembleProductEntityList = assembleProductModel.getProductsByAssembleId(dataId,corpid, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
            if (commonHelp.isOpenWorkFlow(corpid) && Objects.nonNull(forProcess) && forProcess && Objects.equals(WorkflowOperateEnum.ADD.getType(), operate)) {
                JSONArray inProductArray = data.getJSONArray(AssembleEnum.IN_PRODUCTS.getAttr());
                for (int i = 0; i < inProductArray.size(); i++) {
                    JSONObject jsonObject = inProductArray.getJSONObject(i);
                    refProductSeqMap.put(jsonObject.getLong(BusinessConstant.REF_PRODUCT_ID), jsonObject.getJSONArray(ProductConstant.SEQ));
                }
                JSONArray outProductArray = data.getJSONArray(AssembleEnum.OUT_PRODUCTS.getAttr());
                for (int i = 0; i < outProductArray.size(); i++) {
                    JSONObject jsonObject = outProductArray.getJSONObject(i);
                    refProductSeqMap.put(jsonObject.getLong(BusinessConstant.REF_PRODUCT_ID), jsonObject.getJSONArray(ProductConstant.SEQ));
                }
            }
            List<Long> refIdList = new ArrayList<>();
            assembleProductEntityList.forEach(item -> {
                refIdList.add(item.getId());
                productIdList.add(item.getProductId());
                JSONArray seqArray = refProductSeqMap.getOrDefault(item.getId(), null);
                if (Objects.nonNull(seqArray)) {
                    item.getData().put(ProductConstant.SEQ, seqArray);
                }
            });
            if (refIdList.isEmpty()){
                return;
            }
            productBaseInfoEntityList =  productBaseInfoModel.getProductBaseInfoList(corpid,XbbRefTypeEnum.ASSEMBLE_PRODUCT.getCode(),refIdList);
        }
        // baseInfo
        Map<Long,ProductBaseInfoEntity> baseInfoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (ProductBaseInfoEntity entity : productBaseInfoEntityList){
            baseInfoMap.put(entity.getRefId(),entity);
        }

        // 批次库存
        Set<Long> warehouseIdList = new HashSet<>();
        Set<String> batchList = new HashSet<>();
        Set<String> warehouseKeySet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        assembleProductEntityList.forEach(item -> {
            warehouseIdList.add(item.getWarehouseId());
            warehouseKeySet.add(item.getProductId() + "_" + item.getWarehouseId());
            ProductBaseInfoEntity productBaseInfoEntity = baseInfoMap.get(item.getId());
            if (baseInfoMap.containsKey(item.getId()) && StringUtil.isNotEmpty(productBaseInfoEntity.getBatch())) {
                batchList.add(BatchKeyHelp.getBatchKey(item.getProductId(), item.getWarehouseId(), productBaseInfoEntity.getBatch(), productBaseInfoEntity.getProduceDate(), productBaseInfoEntity.getGuaranteePeriod()));
            }
        });
        Map<String, Double> productBatchWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!warehouseIdList.isEmpty() && !batchList.isEmpty()) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put(ParameterConstant.CORPID, corpid);
            params.put("batchKeyIn", batchList);
            List<ProductStockEntity> productStockEntities = productStockModel.findEntitys(params);
            productStockEntities.forEach(item -> {
                productBatchWarehouseMap.put(item.getBatchKey(), item.getNum());
            });
        }
        // 分仓库存
        Map<String, Double> productWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, String> warehouseNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (!productIdList.isEmpty() && !warehouseIdList.isEmpty()) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put(ParameterConstant.CORPID, corpid);
//            params.put("productIdIn", productIdList);
//            params.put("warehouseIdIn", warehouseIdList);
            params.put("warehouseKeyIn",warehouseKeySet);
            List<ProductWarehouseEntity> productWarehouseEntities = productWarehouseModel.findEntitysWithWarehouseChecked(params,null);
            productWarehouseEntities.forEach(item -> {
                String key = item.getProductId() + "_" + item.getWarehouseId();
                productWarehouseMap.put(key, item.getNum());
                warehouseNameMap.put(item.getWarehouseId(),item.getWarehouseName());
            });
            params.clear();
            params.put("del", DelEnum.NORMAL.getDel());
            params.put(ParameterConstant.CORPID, corpid);
            params.put("idIn", warehouseIdList);
            List<WarehouseEntityExt> warehouseEntities = warehouseModel.findEntitys(params);
            warehouseEntities.forEach(item -> {
                warehouseNameMap.put(item.getId(),item.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
            });

        }

        JSONArray outProductArray = new JSONArray();
        JSONArray inProductArray = new JSONArray();
        for (AssembleProductEntity assembleProductEntity : assembleProductEntityList){
//            if (!baseInfoMap.containsKey(assembleProductEntity.getId())) {
//                continue;
//            }
            ProductBaseInfoEntity productBaseInfoEntity = baseInfoMap.getOrDefault(assembleProductEntity.getId(),new ProductBaseInfoEntity());
            if (Objects.equals(assembleProductEntity.getType(),1)){
                JSONObject json = formatSingleProduct(assembleProductEntity,productBaseInfoEntity);
                if (StringUtil.isEmpty(productBaseInfoEntity.getBatch())) {
                    String key = assembleProductEntity.getProductId() + "_" + assembleProductEntity.getWarehouseId();
                    json.put(AssembleProductEnum.STOCK.getAttr(), productWarehouseMap.getOrDefault((key),0D));
                } else {
                    String key = BatchKeyHelp.getBatchKey(assembleProductEntity.getProductId(),assembleProductEntity.getWarehouseId(), productBaseInfoEntity.getBatch(), productBaseInfoEntity.getProduceDate(), productBaseInfoEntity.getGuaranteePeriod());
                    json.put(AssembleProductEnum.STOCK.getAttr(), productBatchWarehouseMap.get(key));
                }
                if (updateDataTypeEnum.isUpdate()){
                    json.put(BusinessConstant.PRODUCT_SUB_ID,assembleProductEntity.getId());
                    if (Objects.isNull(assembleProductEntity.getId())) {
                        json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                    }
                }else {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
                // 工作流生成入库单，需要此属性，所以增加一个
                json.put(BusinessConstant.REF_PRODUCT_ID, json.get(BusinessConstant.PRODUCT_SUB_ID));
                if (updateDataTypeEnum.isLinkAdd()){
                    json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(assembleProductEntity.getCorpid(),assembleProductEntity.getProductUnit()));
                }
                JSONObject warehouseObj = new JSONObject();
                warehouseObj.put("id",json.getLong(AssembleProductEnum.WAREHOUSE.getAttr()));
                warehouseObj.put("name",warehouseNameMap.getOrDefault(assembleProductEntity.getWarehouseId(),""));
                json.put(AssembleProductEnum.WAREHOUSE.getAttr(),Collections.singletonList(warehouseObj));
                JSONObject batchObj = new JSONObject();
                batchObj.put("text",json.getString(AssembleProductEnum.BATCH.getAttr()));
                batchObj.put("value",json.getString(AssembleProductEnum.BATCH.getAttr()));
                json.put(AssembleProductEnum.BATCH.getAttr(),batchObj);
                json.put("editableSerial", 1);
                outProductArray.add(json);
            }else {
                JSONObject json = formatSingleProduct(assembleProductEntity,productBaseInfoEntity);
                // 入库的就算填了批次应该也是显示仓库库存
//                String key = assembleProductEntity.getProductId() + "_" + assembleProductEntity.getWarehouseId();
                if (StringUtil.isEmpty(productBaseInfoEntity.getBatch())) {
                    String key = assembleProductEntity.getProductId() + "_" + assembleProductEntity.getWarehouseId();
                    json.put(AssembleProductEnum.STOCK.getAttr(), productWarehouseMap.getOrDefault((key),0D));
                } else {
                    String key = BatchKeyHelp.getBatchKey(assembleProductEntity.getProductId(),assembleProductEntity.getWarehouseId(), productBaseInfoEntity.getBatch(), productBaseInfoEntity.getProduceDate(), productBaseInfoEntity.getGuaranteePeriod());
                    json.put(AssembleProductEnum.STOCK.getAttr(), productBatchWarehouseMap.get(key));
                }
                if (updateDataTypeEnum.isUpdate()){
                    json.put(BusinessConstant.PRODUCT_SUB_ID,assembleProductEntity.getId());
                    if (Objects.isNull(assembleProductEntity.getId()) || assembleProductEntity.getId() < 0L) {
                        json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                    }
                }else {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
                if (updateDataTypeEnum.isLinkAdd()){
                    json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(assembleProductEntity.getCorpid(),assembleProductEntity.getProductUnit()));
                }
                JSONObject warehouseObj = new JSONObject();
                warehouseObj.put("id",json.getLong(AssembleProductEnum.WAREHOUSE.getAttr()));
                warehouseObj.put("name",warehouseNameMap.getOrDefault(assembleProductEntity.getWarehouseId(),""));
                json.put(AssembleProductEnum.WAREHOUSE.getAttr(),Collections.singletonList(warehouseObj));
                json.put("editableSerial", 1);
                inProductArray.add(json);
            }
        }
        data.put(AssembleEnum.OUT_PRODUCTS.getAttr(),outProductArray);
        data.put(AssembleEnum.IN_PRODUCTS.getAttr(),inProductArray);
    }

    @Override
    public JSONObject formatSingleProduct(AssembleProductEntity assembleProductEntity,ProductBaseInfoEntity productBaseInfoEntity) {
        JSONObject json = assembleProductEntity.getData();
        showFormatHelp.approvalSetBusinessUnit(json, assembleProductEntity);
        if (Objects.isNull(json) || json.isEmpty()){
            json = new JSONObject();
            for (AssembleProductEnum assembleProductEnum :AssembleProductEnum.values()){
                String attr = assembleProductEnum.getAttr();
                switch (assembleProductEnum){
                    case PRODUCT:
                        json.put(attr,assembleProductEntity.getProductId());
                        break;
                    case NUM:
                        json.put(attr,assembleProductEntity.getProductNum());
                        break;
                    case MEMO:
                        json.put(attr,productBaseInfoEntity.getMemo());
                        break;
                    case WAREHOUSE:
                        json.put(attr,assembleProductEntity.getWarehouseId());
                        break;
                    case COST:
                        json.put(attr,assembleProductEntity.getCost());
                        break;
                    case TOTAL_COST:
                        if (Objects.isNull(assembleProductEntity.getProductNum()) || Objects.isNull(assembleProductEntity.getCost())){
                            json.put(attr, 0);
                        } else {
                            json.put(attr, assembleProductEntity.getProductNum() * assembleProductEntity.getCost());
                        }
                        break;
                    case UNIT:
                        json.put(attr,assembleProductEntity.getProductUnit());
                        break;
                    default:
                        break;
                }
            }
        } else if (Objects.equals(json.getDouble(SelectProductEnum.GUARANTEE_PERIOD.getAttr()), 0D)) {
            if (Objects.equals(json.getLong(SelectProductEnum.PRODUCE_DATE.getAttr()), 0L) || Objects.isNull(json.get(SelectProductEnum.PRODUCE_DATE.getAttr()))) {
                json.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
            }
        }
        return json;
    }

    private void formatProductList(String corpid, List<AssembleProductEntity> assembleProducts, List<ProductBaseInfoEntity> productBaseInfoList, JSONArray productArray, Map<Long, ProductEntityExt> productMap, Integer type) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // 仓库
            JSONObject warehouse = FastJsonHelper.getJsonObjectFromFormData(productArrayJSONObject, RelativeProductEnum.WAREHOUSE.getSaasAttr());
            Long warehouseId = 0L;
            if (warehouse != null && warehouse.size() > 0) {
                warehouseId = FastJsonHelper.getLongOrDefaultFromFormData(warehouse, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            }
            // 批次
            String batch = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.BATCH.getSaasAttr(), "");
            // 生产日期
            Long date = DateTimeUtil.getInt(FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.PRODUCE_DATE.getSaasAttr(), ""), DateUtil.SDFDate);
            // 保质期 存的是天数
            Long guaranteePeriod = FastJsonHelper.getLongFromFormData(productArrayJSONObject, RelativeProductEnum.GUARANTEE_PERIOD.getSaasAttr());
            // 产品备注
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            // 成本
            Double cost = getDoubleOrDefaultFromFormData(productArrayJSONObject, StringConstant.PRODUCT_COST, 0D);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                Double stock = getDoubleOrDefaultFromFormData(productObject, ProductEnum.STOCK.getAttr(), 0D);
                AssembleProductEntity productEntity = new AssembleProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setType(type);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setProductPrice(price);
                productEntity.setProductUnit(unit);
                productEntity.setCost(cost);
                productEntity.setProductSpecification(specification);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setSort(sort);
                // 增加关联id 为了和baseInfo有关联
                Long id = new Random().nextLong();
                productEntity.setId(id);
                assembleProducts.add(productEntity);

                // baseInfo冗余信息
                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setBatch(batch);
                if (guaranteePeriod != null) {
                    productBaseInfoEntity.setGuaranteePeriod(guaranteePeriod*86400);
                }
                productBaseInfoEntity.setProduceDate(date);
                productBaseInfoEntity.setRefId(id);
                productBaseInfoEntity.setRefType(XbbRefTypeEnum.ASSEMBLE_PRODUCT.getCode());
                productBaseInfoEntity.setMemo(memo);
                productBaseInfoList.add(productBaseInfoEntity);
            }
        }
    }

    private void formatNewProductList(String corpid, List<AssembleProductEntity> inventoryProducts, List<ProductBaseInfoEntity> productBaseInfoList, JSONArray productArray, Map<Long, ProductEntityExt> productMap, Integer type) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            sort++;
            JSONObject pageProductObject = productArray.getJSONObject(i);
            Long pageProductId = pageProductObject.getLong(AssembleProductEnum.PRODUCT.getAttr());
            Double stock = getDoubleOrDefaultFromFormData(pageProductObject, AssembleProductEnum.STOCK.getAttr(), 0D);
            Double productNum = getDoubleOrDefaultFromFormData(pageProductObject, AssembleProductEnum.NUM.getAttr(), 0D);
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(pageProductObject, AssembleProductEnum.MEMO.getAttr(), "");
            String batch = FastJsonHelper.getStringOrDefaultFromFormData(pageProductObject, AssembleProductEnum.BATCH.getAttr(), "");
            Long date = FastJsonHelper.getLongOrDefaultFromFormData(pageProductObject, AssembleProductEnum.PRODUCE_DATE.getAttr(), 0L);
            Long guaranteePeriod = FastJsonHelper.getLongOrDefaultFromFormData(pageProductObject, AssembleProductEnum.GUARANTEE_PERIOD.getAttr(), 0L);
            Long warehouseId = 0L ;
            if (pageProductObject.get(AssembleProductEnum.WAREHOUSE.getAttr()) instanceof List) {
                // 新建进审批和编辑进审批的格式未统一，导致界面显示不正确，本次更改将仓库id取出
                JSONArray jsonArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(pageProductObject, AssembleProductEnum.WAREHOUSE.getAttr(), new JSONArray());
                if (Objects.nonNull(jsonArray)) {
                    for (int j = 0; j < jsonArray.size(); j++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(j);
                        warehouseId = FastJsonHelper.getLongOrDefaultFromFormData(jsonObject, "id", 0L);
                        break;
                    }
                }
            } else {
                warehouseId = FastJsonHelper.getLongOrDefaultFromFormData(pageProductObject, AssembleProductEnum.WAREHOUSE.getAttr(), 0L);
            }
            Double cost = getDoubleOrDefaultFromFormData(pageProductObject, AssembleProductEnum.COST.getAttr(), 0D);
            Long subProductId = FastJsonHelper.getLongFromFormData(pageProductObject, BusinessConstant.PRODUCT_SUB_ID);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                boolean enableMultiUnit = Objects.equals(productObject.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()),1);
                AssembleProductEntity productEntity = new AssembleProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductPrice(price);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setProductSpecification(specification);
                productEntity.setProductUnit(unit);
                productEntity.setSort(sort);
                productEntity.setType(type);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(AssembleProductEnum.PRODUCT.getAttr(),pageProductId);
                jsonObject.put(AssembleProductEnum.NUM.getAttr(), productNum);
                jsonObject.put(AssembleProductEnum.STOCK.getAttr(), stock);
                jsonObject.put(AssembleProductEnum.MEMO.getAttr(), memo);
                jsonObject.put(AssembleProductEnum.BATCH.getAttr(), batch);
                jsonObject.put(AssembleProductEnum.PRODUCE_DATE.getAttr(), date);
                jsonObject.put(AssembleProductEnum.UNIT.getAttr(), unit);
                jsonObject.put(AssembleProductEnum.COST.getAttr(), cost);
                jsonObject.put(AssembleProductEnum.TOTAL_COST.getAttr(), cost * productNum);
                jsonObject.put(AssembleProductEnum.WAREHOUSE.getAttr(), warehouseId);
                if (enableMultiUnit) {
                    productEntity.setProductUnit(pageProductObject.getString(ProductEnum.UNIT.getAttr()));
                    jsonObject.put(InventoryProductEnum.UNIT.getAttr(), pageProductObject.get(ProductEnum.UNIT.getAttr()));
                }
                for (String attr : pageProductObject.keySet()) {
                    if (!jsonObject.containsKey(attr)) {
                        jsonObject.put(attr, pageProductObject.get(attr));
                    }
                }
                productEntity.setData(jsonObject);

                // 增加关联id 为了和baseInfo有关联
                Long id = Long.valueOf(-sort);
                if (Objects.nonNull(subProductId)) {
                    id = subProductId;
                }
                productEntity.setId(id);
                inventoryProducts.add(productEntity);
                // baseInfo冗余信息

                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setBatch(batch);
                if (guaranteePeriod != null) {
                    productBaseInfoEntity.setGuaranteePeriod(guaranteePeriod * 86400);
                    jsonObject.put(AssembleProductEnum.GUARANTEE_PERIOD.getAttr(), guaranteePeriod);
                }
                productBaseInfoEntity.setProduceDate(date);
                productBaseInfoEntity.setRefId(id);
                productBaseInfoEntity.setRefType(XbbRefTypeEnum.ASSEMBLE_PRODUCT.getCode());
                productBaseInfoEntity.setMemo(memo);
                productBaseInfoList.add(productBaseInfoEntity);
            }
        }
    }
}
